package com.dapao.service.impl;

import com.dapao.mapper.TimeMapper;
import com.dapao.pojo.Time;
import com.dapao.service.TimeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class TimeServiceImpl implements TimeService {

    @Autowired
    private TimeMapper timeMapper;

    @Override
    public void addTimeSlot(Time timeSlot) {
        timeMapper.addTimeSlot(timeSlot);
    }

    @Override
    public List<Time> getAvailableTimeSlots() {
        List<Time> allTimeSlots = timeMapper.getAllTimeSlots();
        return allTimeSlots.stream()
                .filter(this::isTimeSlotValid)
                .collect(Collectors.toList());
    }

    private boolean isTimeSlotValid(Time timeSlot) {
        LocalTime startTime = timeSlot.getStartTime().toLocalTime();
        LocalTime endTime = timeSlot.getEndTime().toLocalTime();
        return !(startTime.isAfter(LocalTime.of(22, 0)) && endTime.isBefore(LocalTime.of(8, 0)));
    }

    @Override
    public Time findCommonAvailableTimeSlot() {
        List<Time> allTimeSlots = getAvailableTimeSlots();
        if (allTimeSlots.isEmpty()) {
            return null; // 没有可用的时间槽
        }

        // 按用户分组时间槽
        Map<Integer, List<Time>> userTimeSlots = allTimeSlots.stream()
                .collect(Collectors.groupingBy(Time::getUserId));

        // 查找共同可用的时间槽
        Time commonTimeSlot = null;
        for (List<Time> userSlots : userTimeSlots.values()) {
            for (Time slot : userSlots) {
                if (isCommonAvailable(slot, userTimeSlots)) {
                    commonTimeSlot = slot;
                    break;
                }
            }
            if (commonTimeSlot != null) {
                break;
            }
        }

        return commonTimeSlot;
    }

    private boolean isCommonAvailable(Time slot, Map<Integer, List<Time>> userTimeSlots) {
        for (List<Time> userSlots : userTimeSlots.values()) {
            boolean found = false;
            for (Time userSlot : userSlots) {
                if (slot.getStartTime().equals(userSlot.getStartTime()) && slot.getEndTime().equals(userSlot.getEndTime())) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                return false;
            }
        }
        return true;
    }
}
